package com.atguigu.guli.service.oss.controller.admin;

import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.oss.service.FileService;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.sun.media.jfxmedia.logging.Logger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.Module;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.GET;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: jinlu
 * @Date: 2022/2/20
 * @Time: 21:24
 * @Version:
 */
@Slf4j
@CrossOrigin // 跨域
@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/admin/oss/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("文件删除")
    @DeleteMapping("remove")
    public R removeFile(@ApiParam(value = "要删除的文件路径"  , required = true) @RequestParam("url") String url){
        fileService.removeFile(url);
        return R.ok().message("文件删除成功！");
    }


    @ApiOperation("测试open feign")
    @GetMapping("test")
    public R test(){
        log.info("oss test被调用");
//        try {
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return R.ok().message("返回消息： oss test被调用");
    }



    @PostMapping("file")
    public R upload(@ApiParam(value = "文件" , required = true) @RequestParam("file") MultipartFile file ,
                    @ApiParam(value = "模块" , required = true) @RequestParam("module") String module) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String uploadUrl = fileService.upload(inputStream, module, originalFilename);
        return R.ok().message("文件上传成功").data("url" , uploadUrl);
    }


    @PostMapping("csv")
    public R csv(@ApiParam(value = "文件" , required = true) @RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        List<String[]> list = read(inputStream,"GB2312");
        return R.ok().data("items" , list);
    }





    /**
     * 读取csv文件内容
     * @param inputStream
     * @param code csv文件的编码,如utf8,,gbk
     *
     * @return 返回csv文件中的数据
     * @throws Exception
     */
    public static List<String[]> read(InputStream inputStream, String code) throws Exception{
        //1. 存储csv文件中的内容
        List<String[]> csvList = new ArrayList<String[]>();
        List<String[]> errorList = new ArrayList<String[]>();

        //2. 创建CsvReader
        CsvReader reader = new CsvReader(inputStream, ',', Charset.forName(code));

        //3. 跳过表头,如果需要表头的话，不要写这句
        //reader.readHeaders();

        //4.逐行读入除表头的数据
        while(reader.readRecord()){
            String[] values = reader.getValues();
            if (values[0].equals("123") || values[0].equals("111")){
                errorList.add(values);
            }
            csvList.add(reader.getValues());
        }

        //5. 释放资源
        reader.close();
        return csvList;
    }

    /**
     * 数据写入csv文件
     * @param list UTF-8编码写入csv文件的内容
     * @param filePath 写入的csv文件的指定路劲
     *
     * @throws Exception
     */
    public static void write(List<String[]> list, String filePath) throws Exception{
        CsvWriter wr = new CsvWriter(filePath, ',', Charset.forName("UTF-8"));
        for (int i = 0; i < list.size(); i++) {
            wr.writeRecord(list.get(i));
        }
        wr.close();
    }
}
